/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import Utility.MessageUtility;
import Utility.Utility;
import beans.ErrorBean;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Emyzzz
 */
public class checkLogin extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "postadd";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        ActionForward forward = new ActionForward();
        System.out.println("IN CHECK LOGIN ACTON");

        try {
            if (((String)request.getSession().getAttribute("username")).equals("")) {
                System.out.println("NAME NULL");
                forward = mapping.findForward("login");

            } else if (!((String) request.getSession().getAttribute("username")).equals("")) {
                System.out.println("name not null");
                Utility util = new Utility();
                
                    if (request.getParameter("act").equals("addPost")) {
                        int threadId = Integer.parseInt(request.getParameter("threadid"));
                        if (!util.checkThreadBlocked(threadId)) {
                             forward = mapping.findForward("postadd");
                    }
                        else {
                            ErrorBean errorBean = new ErrorBean();
                            errorBean.setErrorMsg(MessageUtility.BLOCKED_THREAD);
                            errorBean.setDate(new Date().toString());
                            errorBean.setType("thread Blocked");
                            request.setAttribute("error", errorBean);
                            return mapping.findForward("error");
                    }
                }
                else if(request.getParameter("act").equals("addThread")) {
                        forward = mapping.findForward("addThread");  //addThread
                    }
            }

        } catch (Exception e) {
            e.printStackTrace();
            forward = mapping.findForward("login");
        }
        return forward;
    }
}
